package keke;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TestUnSynchronizedThread {//201521123006
	public static void main(String[] args) throws InterruptedException {
		final CountDownLatch latch = new CountDownLatch(6);
		ExecutorService exec = Executors.newCachedThreadPool();
		for(int i=0;i<3;i++){
			exec.execute( new Adder(latch));
		}
		for(int i=0;i<3;i++){
			exec.execute( new Subtracter(latch));
		}
		exec.shutdown();
        latch.await();
		System.out.println(Counter.getId());
		System.out.println("main end");
	}
}
class Adder implements Runnable {
	CountDownLatch latch;
	public Adder(CountDownLatch latch) {
		this.latch=latch;
	}
	@Override
	public void run() {
		for (int i = 0; i < 10000; i++)
			Counter.addId();
		System.out.println(Thread.currentThread().getName() + " end");
		latch.countDown();
	}
}
class Subtracter implements Runnable {
	CountDownLatch latch;
	public Subtracter(CountDownLatch latch) {
		this.latch=latch;
	}
	@Override
	public void run() {
		for (int i = 0; i < 10000; i++)
			Counter.subtractId();
		System.out.println(Thread.currentThread().getName() + " end");
		latch.countDown();
	}
}
class Counter {
	private static int id = 0;
	public static synchronized void addId() {
		id++;
	}
	public static synchronized void subtractId() {
		id--;
	}
	public static int getId() {
		return id;
	}
}
